const path = require('path');
const fs = require('fs-extra');

const MANIFEST_FILE_NAME = 'manifest.json';

function getImageManifestPath({ zipFileHash, pdfFileHash, uuid }) {
    const userPath = path.join(global.__rootDir, 'uploads', uuid);
    const pdfDir = path.join(userPath, zipFileHash, pdfFileHash);
    fs.mkdirp(pdfDir);
    const manifestPath = path.join(pdfDir, MANIFEST_FILE_NAME);
    return manifestPath;
}
exports.getImageManifestPath = getImageManifestPath;

exports.getImageManifest = function ({ zipFileHash, pdfFileHash, uuid }) {
    const manifestPath = getImageManifestPath({
        zipFileHash,
        pdfFileHash,
        uuid,
    });
    let manifest;
    if (fs.existsSync(manifestPath)) {
        manifest = fs.readFileSync(manifestPath, { encoding: 'utf-8' });
    }
    if (typeof manifest === 'string') {
        manifest = JSON.parse(manifest);
    }
    if (!manifest) {
        manifest = {
            zipFileHash,
            uuid,
            pdfFileHash,
            imageList: [],
        };
    }
    return manifest;
};

exports.writeImageManifest = function ({
    zipFileHash,
    pdfFileHash,
    uuid,
    manifest,
}) {
    const manifestPath = getImageManifestPath({
        zipFileHash,
        pdfFileHash,
        uuid,
    });
    if (!manifest) {
        console.error(
            `zip: ${zipFileHash}, pdf: ${pdfFileHash}, uuid: ${uuid}`
        );
        throw new Error('无法写入空manifest');
    }
    fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 4), {
        encoding: 'utf-8',
    });
    return manifestPath;
};
